package com.example.dellpc.myapplication;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.example.adapter.RecyclerAdapter;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xlf.nrl.NsRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 刘智强 on 2016/9/2.
 */
public class RecyleActivity extends Activity implements NsRefreshLayout.NsRefreshLayoutController, NsRefreshLayout.NsRefreshLayoutListener {

    private String TAG = this.getClass().getName();
    @ViewInject(R.id.recyclerview)
    private RecyclerView recyclerView;
    @ViewInject(R.id.btn_ad)
    private Button btn_ad;
    @ViewInject(R.id.btn_updat)
    private Button btn_update;
    @ViewInject(R.id.btn_delet)
    private Button btn_delete;
    @ViewInject(R.id.nrl_test)
    private NsRefreshLayout nsRefreshLayout;

    private RecyclerAdapter recyclerAdapter;
    private List<Item> items;
    private boolean isLoad = false;

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.what;
            switch (code) {
                case 0:
                    break;

                case 1:
                    Log.e(TAG, recyclerAdapter.getItemCount() + "");
                    recyclerAdapter.getFooterView().setVisibility(View.GONE);
                    recyclerAdapter.getFooterView().setPadding(0, -recyclerAdapter.getFooterView().getHeight(), 0, 0);

                    break;
                default:
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recycleviewactivity);
        ViewUtils.inject(this);
        init();
    }

    public void init() {
        initData();


        recyclerAdapter = new RecyclerAdapter(getApplicationContext(), items);
        /**
         * 这个一看就知道线性布局管理，构造方法有三个参数，第一个上下文对象（不描述）,第二个是一个int型的参数（只能是0和1）0代表横向，1代表纵向，第三个参数Boolean表示顺序还是倒序

         false代表顺序，true代表倒序；这种布局管理器的效果和ListView的效果是一样的一行只能放一个item

         第二种GridLayoutManager

         这个一看就知道是网格布局管理器，也就是说用这种管理器可在一行放多个item，它有两个参数；第一个上下文对象化，第二个int型表示一行放的item的个数（1：表示一行放一个item;2:表示一行放2个item）
         */
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this, 1, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(recyclerAdapter);
        recyclerAdapter.setHeaderView(LayoutInflater.from(getApplicationContext()).inflate(R.layout.recyclerview_headerview, recyclerView, false));
        recyclerAdapter.setFooterView(LayoutInflater.from(this).inflate(R.layout.recyclerview_footerview, recyclerView, false));
        recyclerAdapter.setOnItemClick(new RecyclerAdapter.onItemClick() {
            @Override
            public void onClick(View v, int position) {
                Utils.toast(getApplicationContext(), items.get(position - 1).getTitle());
            }

            @Override
            public void onLongClick() {

            }
        });
        recyclerView.addItemDecoration(new DividerLine(getApplicationContext(), LinearLayoutManager.VERTICAL));


    }

    public void initData() {
        nsRefreshLayout.setRefreshLayoutController(this);
        nsRefreshLayout.setRefreshLayoutListener(this);
        items = new ArrayList<>();
        Item item1 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/2264de11-f174-4cbb-94c9-a7c127bdf7cf.jpg", "泽井芽衣");
        Item item2 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/e9eb0975-11d7-4773-9849-d1dd8b335235.jpg", "大浦安娜");
        Item item3 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/cc6eca55-8406-41ca-8c3a-07b170995632.jpg", "卯月麻衣");
        Item item4 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/e1865497-91e8-49c6-9a8b-ff748cd645e6.jpg", "泷泽萝拉");
        Item item5 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/d30e6e28-b478-48b2-bc58-eaff0fe0d71f.jpg", "樱井莉亚");
        Item item6 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/38d687f1-8408-45fc-88b4-e8aba509d45e.jpg", "雾岛奈津美");
        Item item7 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/76cda128-6bdc-4104-ae30-479b5c4837e7.jpg", "杉原杏璃");
        Item item8 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/3007618a-e7ed-4427-b28b-f76ed6f028f1.jpg", "雨宫琴音");
        Item item9 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/b182b826-0003-417d-b42d-e525ce9d8c83.jpg", "松岛枫");
        Item item10 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/f74c90a0-96bd-4d5b-976c-857ad4110ec3.jpg", "京香julia");
        Item item11 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/c754f960-f656-43f5-80b6-aa10e9cb3bf0.jpg", "波多野结衣");
        Item item12 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/47dba201-cfd7-428d-a2bb-5d5b0ad26bf1.jpg", "仁科百华");
        Item item18 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/98f61aec-9146-4ad8-a7df-56fd26fef543.jpg", "柚木提娜");
        Item item13 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/7af36935-4873-42f9-ae3e-3e42ec5ed1b5.jpg", "仁科百华");
        Item item14 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/71409119-19db-4037-a56e-dc7809c61d06.jpg", "立花美凉");
        Item item15 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/ead3330b-c1a0-4767-bce7-27dd7fdeb07f.jpg", "大桥未久");
        Item item16 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/960b89ab-7666-4c1c-87be-708acf0416c1.jpg", "美祢藤");
        Item item17 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/66c1b537-9842-4118-96d5-10baa447b171.jpg", "天海翼");
        Item item19 = new Item("http://xwimg.app111.org/0x0/2014/12/10/11/ca072c37-ec46-47d8-815d-5ebd76de6b08.jpg", "上原亚衣");
        items.add(item1);
        items.add(item2);
        items.add(item3);
        items.add(item4);
        items.add(item5);
        items.add(item6);
        items.add(item7);
        items.add(item8);
        items.add(item9);
        items.add(item10);
        items.add(item11);
        items.add(item12);
        items.add(item13);
        items.add(item14);
        items.add(item15);
        items.add(item16);
        items.add(item17);
        items.add(item18);
        items.add(item19);
    }

    @OnClick({R.id.btn_ad, R.id.btn_updat, R.id.btn_delet})
    public void onClick(Button button) {
        switch (button.getId()) {
            case R.id.btn_ad:

                Item item1 = new Item("http://i2.sinaimg.cn/ent/cr/2014/0110/1229613881.jpg", "蕾(つぼみ)");
                Item item2 = new Item("http://i1.sinaimg.cn/ent/2014/0110/U2956P28DT20140110155601.jpg", " 希岛爱理(希岛あいり)");
                Item item3 = new Item("http://i0.sinaimg.cn/ent/cr/2014/0110/985658765.jpg", "吉泽明步(よしざわ女きほ)");
                items.add(0, item1);
                items.add(1, item2);
                items.add(2, item3);
                recyclerAdapter.notifyItemRangeInserted(0, 3);
                recyclerView.scrollToPosition(0);
                break;

            case R.id.btn_updat:

                break;

            case R.id.btn_delet:
                if (items.size() == 0) {
                    return;
                }
                items.remove(0);
                recyclerAdapter.notifyItemRemoved(0);
                recyclerAdapter.notifyDataSetChanged();
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                break;
            default:
        }

    }

    @Override
    public boolean isPullRefreshEnable() {
        return true;
    }

    @Override
    public boolean isPullLoadEnable() {
        return true;
    }

    @Override
    public void onRefresh() {
//        Item item1 = new Item("http://i2.sinaimg.cn/ent/cr/2014/0110/1229613881.jpg", "蕾(つぼみ)");
//        Item item2 = new Item("http://i1.sinaimg.cn/ent/2014/0110/U2956P28DT20140110155601.jpg", " 希岛爱理(希岛あいり)");
//        Item item3 = new Item("http://i0.sinaimg.cn/ent/cr/2014/0110/985658765.jpg", "吉泽明步(よしざわ女きほ)");
//        items.add(0, item1);
//        items.add(1, item2);
//        items.add(2, item3);
//        recyclerAdapter.notifyItemRangeInserted(0, 3);
//        recyclerView.scrollToPosition(0);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Item item = new Item("http://img1.imgtn.bdimg.com/it/u=2959844607,1774463192&fm=21&gp=0.jpg", "风景");
                items.remove(0);
                recyclerAdapter.notifyDataSetChanged();
                nsRefreshLayout.finishPullRefresh();
            }
        }, 3000);
    }

    @Override
    public void onLoadMore() {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Item item1 = new Item("http://i2.sinaimg.cn/ent/cr/2014/0110/1229613881.jpg", "蕾(つぼみ)");
                Item item2 = new Item("http://i1.sinaimg.cn/ent/2014/0110/U2956P28DT20140110155601.jpg", " 希岛爱理(希岛あいり)");
                Item item3 = new Item("http://i0.sinaimg.cn/ent/cr/2014/0110/985658765.jpg", "吉泽明步(よしざわ女きほ)");
                items.add(item1);
                items.add(item2);
                items.add(item3);
                recyclerAdapter.notifyDataSetChanged();
                nsRefreshLayout.finishPullLoad();
            }
        }, 3000);

    }

    public class Item {
        private String image;
        private String title;

        public Item(String image, String title) {
            this.image = image;
            this.title = title;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }

    public class DividerLine extends RecyclerView.ItemDecoration {
        private Context context;

        private int orientation = LinearLayoutManager.VERTICAL;//横向 还是 纵向分割线  默认 纵向

        /**
         * item之间分割线的size，默认为1
         */
        private int mItemSize = 3;
        private Paint mPaint;//画笔

        public DividerLine(Context context, int oritation) {
            this.context = context;
            this.orientation = oritation;
            if (orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL) {
                throw new IllegalArgumentException("请传入正确的参数");
            }
            mItemSize = (int) TypedValue.applyDimension(mItemSize, TypedValue.COMPLEX_UNIT_DIP, context.getResources().getDisplayMetrics());
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setColor(Color.GRAY);
         /*设置填充*/
            mPaint.setStyle(Paint.Style.FILL);
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            if (orientation == LinearLayoutManager.VERTICAL) {
                drawVertical(c, parent);
            } else {
                drawHorizontal(c, parent);
            }
        }

        /**
         * 绘制纵向 item 分割线
         *
         * @param canvas
         * @param parent
         */
        private void drawVertical(Canvas canvas, RecyclerView parent) {
            final int left = parent.getPaddingLeft();
            final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
            final int childSize = parent.getChildCount();
            for (int i = 0; i < childSize; i++) {
                final View child = parent.getChildAt(i);
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int top = child.getBottom() + layoutParams.bottomMargin;
                final int bottom = top + mItemSize;
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }

        /**
         * 绘制横向 item 分割线
         *
         * @param canvas
         * @param parent
         */
        private void drawHorizontal(Canvas canvas, RecyclerView parent) {
            final int top = parent.getPaddingTop();
            final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
            final int childSize = parent.getChildCount();
            for (int i = 0; i < childSize; i++) {
                final View child = parent.getChildAt(i);
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int left = child.getRight() + layoutParams.rightMargin;
                final int right = left + mItemSize;
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }


        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if (orientation == LinearLayoutManager.VERTICAL) {
                outRect.set(0, 0, 0, mItemSize);
            } else {
                outRect.set(0, 0, mItemSize, 0);
            }
        }


    }
}
